package com.cjx.myself.service.impl.ssrf;

import com.cjx.myself.controller.ssrf.SSRFController;
import com.cjx.myself.service.ssrf.SsrfService;
import com.cjx.myself.util.HttpClientUtils;
import com.cjx.myself.util.Security;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;


@Service
public class SsrfServiceImpl implements SsrfService {

    Logger log = LoggerFactory.getLogger(SSRFController.class);


    public String ssrf1(String url) {
        log.info("[vul] SSRF：" + url);
        return HttpClientUtils.URLConnection(url);
    }


    public String ssrf2(String url) {
        if (!Security.isHttp(url)) {
            return "不允许非http协议!!!";
        } else if (Security.isIntranet(Security.urltoIp(url))) {
            return "不允许访问内网!!!";
        } else {
            return HttpClientUtils.URLConnection(url);
        }
    }


    public String ssrf3(String url) {
        if (!Security.isHttp(url)) {
            return "不允许非http/https协议!!!";
        } else if (!Security.isWhite(url)) {
            return "非可信域名！";
        } else {
            return HttpClientUtils.URLConnection(url);
        }
    }


    public String ssrf4(String url) {
        // 校验 url 是否以 http 或 https 开头
        if (!Security.isHttp(url)) {
            log.error("[HTTPURLConnection] 非法的 url 协议：" + url);
            return "不允许非http/https协议!!!";
        }

        // 解析 url 为 IP 地址
        String ip = Security.urltoIp(url);
        log.info("[HTTPURLConnection] SSRF解析IP：" + ip);

        // 校验 IP 是否为内网地址
        if (Security.isIntranet(ip)) {
            log.error("[HTTPURLConnection] 不允许访问内网：" + ip);
            return "不允许访问内网!!!";
        }

        // 访问 url
        try {
            return HttpClientUtils.HTTPURLConnection(url);
        } catch (Exception e) {
            log.error("[HTTPURLConnection] 访问失败：" + e.getMessage());
            return "访问失败，请稍后再试!!!";
        }
    }
}
